﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.APP_UI.UserControls;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.MODEL;
using KPIS.GERP.GHRMS.BLL;
using Telerik.Web.UI;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project1 : System.Web.UI.Page
    {
        private IProject projectBLL;
        private ComboBLL comboBLL = new ComboBLL();
        private SystemTypeYearBLL sysTypeYearBLL = new SystemTypeYearBLL();
        private EmployeeBLL empBLL = new EmployeeBLL();
        private SystemControlBLL scBLL = new SystemControlBLL();
        private OptionTypeBLL optionTypeBLL = new OptionTypeBLL();
        private SourceBLL source = new SourceBLL();
        private IProjectReaderDtlsBLL ProjectReaderDtls = new ProjectReaderDtlsBLL();
        private IBgmKpiListBLL KpiLis = new BgmKpiListBLL();
        private RequestPass requestPass = new RequestPass();
        private Main main = new Main();
        private SsMng ssMng = new SsMng();

        //============= only bgm_project =============
        private ProjectOperation projectOperation = new ProjectOperation();
        private ManageProject manageProjectBLL = new ManageProject();
        private ProjectControl_BLL ctrl = new ProjectControl_BLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            projectBLL = Project_Factory.GetProjectFactory(Request.QueryString["type"]);

            if (!IsPostBack)
            {
                lblType.Value = Request.QueryString["type"];
                lbBgmYear.Text = Request.QueryString["year"];
                lblJobSiteSeq.Value = Request.QueryString["id"];
                lbProjDate.Text = DateTime.Today.ToString("dd MMMM yyyy", new CultureInfo("th-TH"));

                LoadMasterData();

                if (lblType.Value != "pj")
                {
                    pnlCode.Visible = false;
                    Session["Approve"] = false;
                    ChangeMode(Main.EditMode.View);
                    pnlOperation.Visible = false;
                }
                else
                {
                    pnlCode.Visible = true;
                    Session["ProjectID"] = Request.QueryString["seq"];
                    lblProjectSeq.Value = Request.QueryString["seq"];
                    SetProjectInfo();
                    Session["Approve"] = true;
                    ChangeMode(Main.EditMode.Info);
                    pnlOperation.Visible = true;
                }
            }

            LoadOption(lblProjectSeq.Value);
        }

        #region Main Region

        private void LoadDtgProj()
        {
            string strUserJobSiteID = ssMng.WorkingJobSiteSeq;
            bool blnIsStrategyJobSite = (strUserJobSiteID == scBLL.JobSiteStrategyID());

            DataTable dtb = projectBLL.GetDataProjectByYearAndJobSite(lbBgmYear.Text, lblJobSiteSeq.Value, "", "");
            dtgProj.DataSource = dtb;
        }

        private void LoadMasterData()
        {
            ddlStrategy.DataSource = comboBLL.ListStrategy(lbBgmYear.Text);
            ddlStrategy.DataBind();

            ddlJobSite.DataSource = comboBLL.ListJobsite();
            ddlJobSite.DataBind();
            ddlJobSite.SelectedValue = lblJobSiteSeq.Value;

            ddlProjType.DataSource = comboBLL.ListProjectTypeWithNewProjectComeFirst();
            ddlProjType.DataBind();

            ddlProjScope.DataSource = comboBLL.ListScope();
            ddlProjScope.DataBind();
        }


        private void LoadGridSource(string strProjectSeq)
        {
            gridSource.DataSource = projectBLL.GetDataProjectBySequenceForGridIn(strProjectSeq);
            gridSource.DataBind();
        }

        private void LoadGridManager(string strProjectSeq)
        {
            gridManager.DataSource = projectBLL.GetDataProjectManager(strProjectSeq);
            gridManager.DataBind();
        }

        private void LoadRepeaterJobSitePass(string strProjectSeq)
        {
            repeaterJobSitePass.DataSource = requestPass.GetData(strProjectSeq);
            repeaterJobSitePass.DataBind();
        }

        private void LoadOption(string strProjectSeq)
        {
            if (strProjectSeq.Length > 0 && PanelOption.Controls.Count == 1)
            {
                IList<OptionTypeInfo> optionTypeInfoList = optionTypeBLL.Search(-1);

                foreach (OptionTypeInfo info in optionTypeInfoList)
                {
                    string strBgmOptionTypeSeq = info.Sequence.ToString();

                    BGM_ProjectOption userControl = (BGM_ProjectOption)Page.LoadControl("~/APP_UI/UserControls/BGM_ProjectOption.ascx");
                     
                    userControl.LoadUserControlData(strBgmOptionTypeSeq, strProjectSeq, lblType.Value);

                    PanelOption.Controls.Add(userControl);
                }
            }
        }

        private BGM_ProjectOption PanelOptionBGM_ProjectOption
        {
            get
            {
                try
                {
                    return PanelOption.Controls.Count > 0 ? (BGM_ProjectOption) PanelOption.Controls[0] : null;
                } catch(Exception ex)
                {
                    return null;
                }
            }
        }

        private void LoadReport5(string strProjectSeq)
        {
            gridReport5.DataSource = manageProjectBLL.GetTransferReport(strProjectSeq);
            gridReport5.DataBind();
        }

        protected void LoadJobSiteEmpHeadInfo(string selectedJobSiteSeq)
        {
            string errorMessage = "";
            DataRow dr = comboBLL.GetJobSiteHeadEmployee(selectedJobSiteSeq, ref errorMessage);
            lblJobSiteHeadPosLoadError.Text = errorMessage;
            if (String.IsNullOrEmpty(errorMessage))
                lblJobSiteHeadPos.Text = dr["fullnamepos"] as string;
        }

        private void ChangeMode(Main.EditMode mode)
        {
            bool blnApproved = (bool) Session["Approve"] && (lblType.Value != "pj");
            switch (mode)
            {
                case Main.EditMode.AddNew:
                    btnAddNew.Visible = false;
                    btnEdit.Visible = false && !blnApproved;
                    btnDelete.Visible = false && !blnApproved;
                    btnPrintPreview.Visible = false;
                    btnApprove.Visible = false && !blnApproved && (lblType.Value != "pj");
                    btnEndProject.Visible = false && !blnApproved && (lblType.Value == "pj");
                    btnSaveAddNew.Visible = true && !blnApproved;
                    btnSaveEdit.Visible = false && !blnApproved;
                    btnCancel.Visible = true;

                    gridSource.Columns[0].Visible = false;
                    btnExpPlan.Enabled = false;
                    btnManager.Enabled = false;
                    btnWorkPlan.Enabled = false;
                    btnKPI.Enabled = false;
                    pnlAssignProjectPopup.Visible = false; //(lblType.Text == "pj");

                    pnlView.Visible = false;
                    pnlInfo.Visible = true;
                    PanelOption.Enabled = false;

                    ViewInfo(false);

                    break;
                case Main.EditMode.Edit:
                    btnAddNew.Visible = false;
                    btnEdit.Visible = false && !blnApproved;
                    btnDelete.Visible = true && !blnApproved;
                    btnPrintPreview.Visible = true;// && (lblType.Value != "pj");
                    btnApprove.Visible = true && !blnApproved && (lblType.Value != "pj");
                    btnEndProject.Visible = true && !blnApproved && (lblType.Value == "pj");
                    btnSaveAddNew.Visible = false && !blnApproved;
                    btnSaveEdit.Visible = true && !blnApproved;
                    btnCancel.Visible = true;

                    gridSource.Columns[0].Visible = true && (lblType.Value != "pj");
                    btnExpPlan.Enabled = true;
                    btnManager.Enabled = true;
                    btnWorkPlan.Enabled = true;
                    btnKPI.Enabled = true;
                    pnlAssignProjectPopup.Visible = (lblType.Value == "pj");

                    pnlView.Visible = false;
                    pnlInfo.Visible = true;
                    PanelOption.Enabled = true;

                    ViewInfo(false);
                    break;
                case Main.EditMode.View:
                    btnAddNew.Visible = true;
                    btnEdit.Visible = false && !blnApproved;
                    btnDelete.Visible = false && !blnApproved;
                    btnPrintPreview.Visible = false;
                    btnApprove.Visible = false && !blnApproved && (lblType.Value != "pj");
                    btnEndProject.Visible = false && !blnApproved && (lblType.Value == "pj");
                    btnSaveAddNew.Visible = false && !blnApproved;
                    btnSaveEdit.Visible = false && !blnApproved;
                    btnCancel.Visible = false;

                    pnlView.Visible = true;
                    pnlInfo.Visible = false;
                    PanelOption.Enabled = true;

                    ViewInfo(false);
                    break;
                case Main.EditMode.Info:
                    btnAddNew.Visible = false;
                    btnEdit.Visible = true && !blnApproved;
                    btnDelete.Visible = true && !blnApproved;
                    btnPrintPreview.Visible = true;// && (lblType.Value != "pj");
                    btnApprove.Visible = true && !blnApproved && (lblType.Value != "pj");
                    btnEndProject.Visible = true && !blnApproved && (lblType.Value == "pj");
                    btnSaveAddNew.Visible = false && !blnApproved;
                    btnSaveEdit.Visible = false && !blnApproved;
                    btnCancel.Visible = true && (lblType.Value != "pj");

                    gridSource.Columns[0].Visible = true && (lblType.Value != "pj");
                    btnExpPlan.Enabled = true;
                    btnManager.Enabled = true;
                    btnWorkPlan.Enabled = true;
                    btnKPI.Enabled = true;
                    pnlAssignProjectPopup.Visible = (lblType.Value == "pj");

                    pnlView.Visible = false;
                    pnlInfo.Visible = true;
                    PanelOption.Enabled = true;

                    ViewInfo(true);
                    break;
            }
        }

        private void ViewInfo(bool blnViewInfo)
        {
            lbProjDate.Visible = blnViewInfo;
            txtProjDate.Visible = !blnViewInfo;
            lblProjCode.Visible = blnViewInfo;
            txtProjCode.Visible = !blnViewInfo;
            lblGFMISCode.Visible = blnViewInfo;
            txtGFMISCode.Visible = !blnViewInfo;
            lbProjName.Visible = blnViewInfo;
            txtProjName.Visible = !blnViewInfo;
            lbProjStrat.Visible = blnViewInfo;
            ddlStrategy.Visible = !blnViewInfo;
            lbProjJobSiteMain.Visible = blnViewInfo;
            ddlJobSite.Visible = !blnViewInfo;
            btnJobSitePass.Visible = !blnViewInfo;

            lblStartDate.Visible = blnViewInfo;
            txtStartDate.Visible = !blnViewInfo;
            lblEndDate.Visible = blnViewInfo;
            txtEndDate.Visible = !blnViewInfo;
            lbProjType.Visible = blnViewInfo;
            ddlProjType.Visible = !blnViewInfo;
            lbProjScope.Visible = blnViewInfo;
            ddlProjScope.Visible = !blnViewInfo;

            lbProjReason.Visible = blnViewInfo;
            txtProjReason.Visible = !blnViewInfo;
            lbProjObject.Visible = blnViewInfo;
            txtProjObject.Visible = !blnViewInfo;
            lbProjTarget.Visible = blnViewInfo;
            txtProjTarget.Visible = !blnViewInfo;
            lbProjPlan.Visible = blnViewInfo;
            txtProjPlan.Visible = !blnViewInfo;
            lbProjAim.Visible = blnViewInfo;
            txtProjAim.Visible = !blnViewInfo;
            lbProjProfit.Visible = blnViewInfo;
            txtProjProfit.Visible = !blnViewInfo;
            lbProjRemark.Visible = blnViewInfo;
            txtProjRemark.Visible = !blnViewInfo;
        }

        private void ClearControl()
        {
            lbProjDate.Text = "";
            txtProjDate.SetValue(null);
            lbProjName.Text = "";
            txtProjName.Text = "";
            lbProjStrat.Text = "";
            ddlStrategy.SelectedIndex = 0;
            lbProjJobSiteMain.Text = "";
            ddlJobSite.SelectedValue = lblJobSiteSeq.Value;

            lblStartDate.Text = "";
            txtStartDate.SetValue(null);
            lblEndDate.Text = "";
            txtEndDate.SetValue(null);
            lbProjType.Text = "";
            ddlProjType.SelectedIndex = 0;
            lbProjScope.Text = "";
            ddlProjScope.SelectedIndex = 0;

            lbProjReason.Text = "";
            txtProjReason.Text = "";
            lbProjObject.Text = "";
            txtProjObject.Text = "";
            lbProjTarget.Text = "";
            txtProjTarget.Text = "";
            lbProjPlan.Text = "";
            txtProjPlan.Text = "";
            lbProjAim.Text = "";
            txtProjAim.Text = "";
            lbProjProfit.Text = "";
            txtProjProfit.Text = "";
            lbProjRemark.Text = "";
            txtProjRemark.Text = "";

            lblApproved.Text = "";

            //LoadGridManager("-1");
            //LoadGridSource("-1");
            //LoadRepeaterJobSitePass("-1");
            //LoadOption("-1");
        }

        private void SetProjectInfo()
        {
            try
            {
                string strProjectSeq = lblProjectSeq.Value;
                DataTable dt = projectBLL.GetDataProjectBySequence(strProjectSeq);

                if (dt.Rows.Count > 0)
                {
                    lbBgmYear.Text = dt.Rows[0]["bgm_year"].ToString();
                    lbProjDate.Text = Convert.ToDateTime(dt.Rows[0]["bgm_prj_date"]).ToString("dd MMMM yyyy", new CultureInfo("th-TH"));
                    lblProjCode.Text = dt.Rows[0]["bgm_prj_code"].ToString();
                    lblGFMISCode.Text = dt.Rows[0]["gfmis_code"].ToString();
                    lbProjName.Text = dt.Rows[0]["bgm_prj_name"].ToString();
                    lbProjStrat.Text = dt.Rows[0]["bgm_strat_list_name"].ToString();
                    lbProjJobSiteSeq.Text = dt.Rows[0]["job_site_seq"].ToString();
                    Session["ProjectJobSiteSeq"] = lbProjJobSiteSeq.Text;
                    lbProjJobSite.Text = dt.Rows[0]["job_site_name"].ToString();
                    lbProjJobSiteMain.Text = dt.Rows[0]["job_site_name_main"].ToString();
                    lbProjType.Text = dt.Rows[0]["prj_type_name"].ToString();
                    lbProjScope.Text = dt.Rows[0]["bgm_scope_name"].ToString();

                    lbProjReason.Text = (dt.Rows[0]["bgm_prj_reason"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_reason"].ToString())
                        : "-";
                    lbProjObject.Text = (dt.Rows[0]["bgm_prj_object"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_object"].ToString())
                        : "-";
                    lbProjTarget.Text = (dt.Rows[0]["bgm_prj_target"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_target"].ToString())
                        : "-";
                    lbProjPlan.Text = (dt.Rows[0]["bgm_prj_plan"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_plan"].ToString())
                        : "-";
                    lbProjAim.Text = (dt.Rows[0]["bgm_prj_aim"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_aim"].ToString())
                        : "-";
                    lbProjProfit.Text = (dt.Rows[0]["bgm_prj_profit"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_profit"].ToString())
                        : "-";
                    lbProjRemark.Text = (dt.Rows[0]["bgm_prj_remark"].ToString().Length > 0)
                        ? main.WebString(dt.Rows[0]["bgm_prj_remark"].ToString())
                        : "-";
                    lblStartDate.Text = Convert.ToDateTime(dt.Rows[0]["date_start"]).ToString("dd/MM/yyyy", new CultureInfo("th-TH"));
                    lblEndDate.Text = Convert.ToDateTime(dt.Rows[0]["date_end"]).ToString("dd/MM/yyyy", new CultureInfo("th-TH"));

                    lbBgmYear.Text = dt.Rows[0]["bgm_year"].ToString();
                    txtProjDate.SetValue(dt.Rows[0]["bgm_prj_date"]);
                    txtProjName.Text = dt.Rows[0]["bgm_prj_name"].ToString();
                    txtProjCode.Text = dt.Rows[0]["bgm_prj_code"].ToString();
                    txtGFMISCode.Text = dt.Rows[0]["gfmis_code"].ToString();
                    ddlStrategy.SelectedValue = dt.Rows[0]["bgm_strat_list_seq"].ToString();
                    ddlStrategy.Text = dt.Rows[0]["bgm_strat_list_name"].ToString();
                    ddlJobSite.SelectedValue = dt.Rows[0]["job_site_seq_main"].ToString();
                    ddlJobSite.Text = dt.Rows[0]["job_site_name_main"].ToString();
                    ddlProjType.SelectedValue = dt.Rows[0]["prj_type_seq"].ToString();
                    ddlProjType.Text = dt.Rows[0]["prj_type_name"].ToString();
                    ddlProjScope.SelectedValue = dt.Rows[0]["bgm_prj_scope"].ToString();
                    ddlProjScope.Text = dt.Rows[0]["bgm_scope_name"].ToString();

                    txtProjReason.Text = (dt.Rows[0]["bgm_prj_reason"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_reason"].ToString()
                        : "-";
                    txtProjObject.Text = (dt.Rows[0]["bgm_prj_object"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_object"].ToString()
                        : "-";
                    txtProjTarget.Text = (dt.Rows[0]["bgm_prj_target"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_target"].ToString()
                        : "-";
                    txtProjPlan.Text = (dt.Rows[0]["bgm_prj_plan"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_plan"].ToString()
                        : "-";
                    txtProjAim.Text = (dt.Rows[0]["bgm_prj_aim"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_aim"].ToString()
                        : "-";
                    txtProjProfit.Text = (dt.Rows[0]["bgm_prj_profit"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_profit"].ToString()
                        : "-";
                    txtProjRemark.Text = (dt.Rows[0]["bgm_prj_remark"].ToString().Length > 0)
                        ? dt.Rows[0]["bgm_prj_remark"].ToString()
                        : "-";
                    txtStartDate.SetValue(dt.Rows[0]["date_start"]);
                    txtEndDate.SetValue(dt.Rows[0]["date_end"]);

                    DataTable dtb = comboBLL.GetInfoFromRefSeq(strProjectSeq, "bgm_request");

                    if (dtb.Rows.Count > 0)
                    {
                        lblReplyRemark.Text = dtb.Rows[0]["remarks"].ToString();
                        PanelReplyRemarks.Visible = (lblReplyRemark.Text.Length > 0);
                    }
                    else
                    {
                        lblReplyRemark.Text = "";
                        PanelReplyRemarks.Visible = false;
                    }

                    LoadGridManager(strProjectSeq);
                    LoadGridSource(strProjectSeq);
                    LoadRepeaterJobSitePass(strProjectSeq);
                    LoadOption(strProjectSeq);
                    LoadJobSiteEmpHeadInfo(lbProjJobSiteSeq.Text);

                    if (lblType.Value == "pj")
                    {
                        LoadReport5(strProjectSeq);
                    }

                    Session["ProjectName"] = lbProjName.Text;

                    //============ เตือนไม่มีข้อมูล ===============
                    DataTable dtb2;
                    dtb2 = projectBLL.GetDataProjectActivityPlan(strProjectSeq);
                    lbWorkPlanEmpty.Visible = (dtb2.Rows.Count == 0);
                    dtb2 = projectBLL.GetDataProjectExpensePlan(strProjectSeq, null);
                    lbExpPlanEmpty.Visible = (dtb2.Rows.Count == 0);
                    //dtb2 = KpiLis.Search(main.ConvertNullInt(strProjectSeq)
                    //    , main.ConvertNullInt(lbBgmYear.Text), null, null, null, null, lblType.Value);//projectBLL.GetDataProjectKPI(strProjectSeq);
                    //lbKPIEmpty.Visible = (dtb2.Rows.Count == 0);
                    dtb2 = ProjectReaderDtls.Search(null, strProjectSeq, null, null, null, null, null);//projectBLL.GetDataProjectKPI(strProjectSeq);
                    lblAssignNoData.Visible = (dtb2.Rows.Count == 0);
                    //=======================================
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        protected void SetSumExpense(DataTable dtb)
        {
            double dblSumExpense = 0;

            foreach (DataRow dtr in dtb.Rows)
            {
                string strGroup = dtr["child_value"].ToString().Split('-')[1];

                if (strGroup == "SOURCE")
                {
                    dblSumExpense += Convert.ToDouble(dtr["cal_amount"]);
                }
            }

            lblSumExpense.Text = dblSumExpense.ToString("#,##0.00");
        }

        private bool CheckData()
        {
            bool blnOK = true;
            string strError = "";

            if (txtProjDate.GetDateValue() == null)
            {
                strError = main.ErrorEmtyString("วันที่บันทึก");
                blnOK = false;
            }
            else if (lblType.Value == "pj" && txtProjCode.Text.Trim().Length == 0)
            {
                strError = main.ErrorEmtyString("รหัสโครงการ");
                blnOK = false;
            }
            else if (lblType.Value == "pj" && txtGFMISCode.Text.Trim().Length == 0)
            {
                strError = main.ErrorEmtyString("รหัส GFMIS");
                blnOK = false;
            }
            else if (txtProjName.Text.Trim().Length == 0)
            {
                strError = main.ErrorEmtyString("ชื่อโครงการ");
                blnOK = false;
            }
            else if (ddlStrategy.SelectedValue.Length == 0)
            {
                strError = main.ErrorEmtyString("กิจกรรมย่อย");
                blnOK = false;
            }
            else if (ddlJobSite.SelectedValue.Length == 0)
            {
                strError = main.ErrorEmtyString("หน่วยงานหลัก");
                blnOK = false;
            }
            else if (txtStartDate.GetDateValue() == null)
            {
                strError = main.ErrorEmtyString("วันที่เริ่มต้น");
                blnOK = false;
            }
            else if (txtEndDate.GetDateValue() == null)
            {
                strError = main.ErrorEmtyString("วันที่สิ้นสุด");
                blnOK = false;
            }
            else if (ddlProjType.SelectedValue.Length == 0)
            {
                strError = main.ErrorEmtyString("ประเภทโครงการ");
                blnOK = false;
            }
            else if (ddlProjScope.SelectedValue.Length == 0)
            {
                strError = main.ErrorEmtyString("พื้นที่ดำเนินการ");
                blnOK = false;
            }

            if (!blnOK)
            {
                main.MessageAlert(Page, strError);
            }

            return blnOK;
        }

        #endregion

        #region Control's Event Region

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            LoadOption("");
            ChangeMode(Main.EditMode.AddNew);
            btnSaveAddNew.Visible = true;
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            LoadOption(lblProjectSeq.Value);
            ChangeMode(Main.EditMode.Edit);
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            projectBLL.DeleteProject(lblProjectSeq.Value, new SsMng().EmpSeq);

            LoadDtgProj();
            dtgProj.DataBind();
            SetProjectInfo();
            ClearControl();
            ChangeMode(Main.EditMode.View);
        }

        protected void btnSaveAddNew_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckData())
                {
                    return;
                }

                // บันทึกโครงการใหม่ พร้อมได้รับค่า ID โครงการใหม่ที่เพิ่งสร้าง
                int reqSeqTemp = projectBLL.InsertProject(lbBgmYear.Text, DateTime.Today
                    , "โครงการ" + txtProjName.Text, ddlStrategy.SelectedValue, lblJobSiteSeq.Value
                    , ddlProjType.SelectedValue, ddlProjScope.SelectedValue, txtProjReason.Text
                    , txtProjObject.Text, txtProjPlan.Text, txtProjTarget.Text, txtProjAim.Text, txtProjProfit.Text, txtProjRemark.Text
                    , txtStartDate.ValueS, txtEndDate.ValueS, ssMng.EmpSeq
                    , ddlJobSite.SelectedValue);

                string reqSeq = Convert.ToString(reqSeqTemp);
                
                // ใส่ผู้รับผิดชอบ#1 เป็นผู้บังคับบัญชาบนสุดตามสายบังคับบัญชา
                DataRow drwEmpHead = comboBLL.GetJobSiteHeadEmployee(lblJobSiteSeq.Value);
                string commanderEmpSeq = "";
                if (drwEmpHead != null && (drwEmpHead["emp_seq"] as int?).HasValue)
                {
                    commanderEmpSeq = Convert.ToString(drwEmpHead["emp_seq"]);
                    projectBLL.InsertProjectManager(reqSeq, commanderEmpSeq);
                }
                // ใส่ผู้รับผิดชอบ#2 เป็นผู้ที่กำลังทำการสร้างโครงการ (กรณีผู้บังคับบัญชาไม่ได้เป็นคนสร้างเอง)
                if (ssMng.EmpSeq != commanderEmpSeq)
                {
                    projectBLL.InsertProjectManager(reqSeq, ssMng.EmpSeq);
                }

                lblProjectSeq.Value = reqSeq;
                Session["ProjectID"] = reqSeq;

                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
                //Page.ClientScript.RegisterStartupScript(GetType(), "Message", "alert('บันทึกเรียบร้อยแล้ว');", true);

                //LoadDtgProj();
                //dtgProj.DataBind();
                ClearControl();
                SetProjectInfo();
                ChangeMode(Main.EditMode.Info);
            }
            catch (Exception error)
            {
                main.MessageAlert(Page, "เกิดข้อผิดพลาดในการบันทึกข้อมูล\n" + main.EncodeHtml(error.Message));
            }
        }

        protected void btnSaveEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckData())
                {
                    return;
                }

                Nullable<DateTime> dateS = txtStartDate.GetDateValue();
                Nullable<DateTime> dateE = txtEndDate.GetDateValue();

                projectBLL.UpdateProject(lblProjectSeq.Value, txtProjDate.GetDateValue().Value, (pnlCode.Visible ? txtProjCode.Text : null)
                    , txtProjName.Text, null, ddlJobSite.SelectedValue, null, ddlProjScope.SelectedValue, txtProjReason.Text
                    , txtProjObject.Text, txtProjTarget.Text, txtProjPlan.Text, txtProjAim.Text, txtProjProfit.Text, txtProjRemark.Text
                    , ddlStrategy.SelectedValue, ddlProjType.SelectedValue
                    , txtStartDate.GetDateValue().Value, txtEndDate.GetDateValue().Value
                    , (pnlCode.Visible ? txtGFMISCode.Text : null), ssMng.EmpSeq);
                main.MessageAlert(Page, "บันทึกเรียบร้อย");

                //LoadDtgProj();
                //dtgProj.DataBind();
                ClearControl();
                SetProjectInfo();
                ChangeMode(Main.EditMode.Info);
            }
            catch (Exception error)
            {
                main.MessageAlert(Page, "เกิดข้อผิดพลาดในการบันทึกข้อมูล\n" + main.EncodeHtml(error.Message));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (lblType.Value != "pj")
            {
                LoadDtgProj();
                dtgProj.DataBind();
                ClearControl();
                ChangeMode(Main.EditMode.View);
            }
            else
            {
                //LoadDtgProj();
                //dtgProj.DataBind();
                //ClearControl();
                ChangeMode(Main.EditMode.Info);
            }
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            string strArg = e.Argument;
            string strProjectSeq = lblProjectSeq.Value;

            if (strArg == "refresh")
            {
                string strRecordStatus = projectBLL.GetDataProjectBySequence(lblProjectSeq.Value).Rows[0]["record_status"].ToString();

                if (strRecordStatus == "P")
                {
                    lblApproved.Text = "รออนุมัติ";
                    btnApprove.Visible = false;
                    btnEdit.Enabled = false;
                }
            }
            else if (strArg == "JobSitePass")
            {
                repeaterJobSitePass.DataSource = requestPass.GetData(strProjectSeq);
                repeaterJobSitePass.DataBind();
            }
            else
            {
                LoadGridSource(strProjectSeq);
                LoadGridManager(strProjectSeq);
                LoadRepeaterJobSitePass(strProjectSeq);
                LoadOption(strProjectSeq);
            }
        }

        protected void dtgProj_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            LoadDtgProj();
        }

        protected void dtgProj_EditCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string strBgmProjSeq = item["Sequence"].Text;
            string strRecordStatus = item["record_status"].Text;
            string strRecordStatusName = item["record_status_name"].Text;

            Session["Approve"] = (strRecordStatus == "P") || (strRecordStatus == "A");
            lblApproved.Text = strRecordStatusName;
            lblProjectSeq.Value = strBgmProjSeq;
            Session["ProjectID"] = strBgmProjSeq;
            SetProjectInfo();
            ChangeMode(Main.EditMode.Info);
        }

        protected void repeaterJobSitePass_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string strProjectSeq = lblProjectSeq.Value;
                Label lblBgmReqPassSeq = (Label)e.Item.FindControl("lblBgmReqPassSeq");
                requestPass.Delete(lblBgmReqPassSeq.Text, ssMng.EmpSeq);

                repeaterJobSitePass.DataSource = requestPass.GetData(strProjectSeq);
                repeaterJobSitePass.DataBind();
            }
        }

        protected void tvlExpense_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            DataTable dtb = manageProjectBLL.GetReportTreeList(lblProjectSeq.Value);
            tvlExpense.DataSource = dtb;

            SetSumExpense(dtb);
        }

        protected void gridReport5_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_exp_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void tvlOperation_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            tvlOperation.DataSource = manageProjectBLL.GetProjectOperationReport(lblProjectSeq.Value);
        }

        protected void tvlOperation_ItemDataBound(object sender, TreeListItemDataBoundEventArgs e)
        {
            if (e.Item.ItemType == TreeListItemType.Item || e.Item.ItemType == TreeListItemType.AlternatingItem)
            {
                TreeListDataItem item = (TreeListDataItem)e.Item;
                bool bRoot = item["child_seq"].Text.Split('/').Length == 2;

                ((Label)item["name"].FindControl("lblName")).Visible = !bRoot;
                ((LinkButton)item["name"].FindControl("cmdViewOperation")).Visible = bRoot;

                if (bRoot)
                {
                    item.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    item.ForeColor = System.Drawing.Color.Black;
                }
            }
        }

        protected void btnEndProject_Click(object sender, EventArgs e)
        {
            string strBgmProjSeq = lblProjectSeq.Value;
            string strEmpSeq = new SsMng().EmpSeq;

            if (projectOperation.CountProjectOperation(strBgmProjSeq) > 0)
            {
                main.MessageAlert(Page, "กรุณาปิดอนุมัติโครงการให้หมดก่อนที่จะปิดโครงการ!!");
                return;
            }

            try
            {
                DataTable dtb = manageProjectBLL.GetProjectExpenseWithRemainAmount(lblProjectSeq.Value, null, null);

                foreach (DataRow dtr in dtb.Rows)
                {
                    Nullable<double> dAmount = main.ConvertNullDouble(dtr["total_amount"]);

                    if (dAmount != null && dAmount > 0)
                    {
                        string strBgmProjCtrlSeq = "";
                        string strBgmProjExpSeq = main.WebString(dtr["bgm_proj_exp_seq"].ToString());
                        string strBgmSourceSeq = main.WebString(dtr["bgm_source_seq"].ToString());
                        string strBgmStratListSeq = main.WebString(dtr["bgm_strat_list_seq"].ToString());
                        string strJobSiteSeq = main.WebString(dtr["job_site_seq"].ToString());
                        string strBgmExpGrpSeq = main.WebString(dtr["bgm_exp_grp_seq"].ToString());
                        string strAmount = main.WebString(dtr["cal_amount"].ToString());

                        DataTable dtbProjectCtrl = ctrl.FindProjectCtrl(lbBgmYear.Text, strBgmStratListSeq, strBgmSourceSeq
                            , strJobSiteSeq, strBgmExpGrpSeq);

                        if (dtbProjectCtrl.Rows.Count > 0)
                        {
                            strBgmProjCtrlSeq = dtbProjectCtrl.Rows[0]["bgm_proj_ctrl_seq"].ToString();
                        }
                        else
                        {
                            strBgmProjCtrlSeq = ctrl.Insert_BgmProjectControl(lbBgmYear.Text, strBgmSourceSeq
                                , strBgmStratListSeq, strJobSiteSeq, strBgmExpGrpSeq, strEmpSeq);
                        }

                        manageProjectBLL.InsertProjectExpenseControl(null, strBgmProjExpSeq, "1", "R", dAmount.ToString(), strEmpSeq);
                        //ctrl.Insert_BgmProjectControlExpense(strBgmProjCtrlSeq, "1", strBgmProjExpSeq, strAmount, strEmpSeq);
                        projectBLL.UpdateTotalAmountProjectExpense(strBgmProjExpSeq, "ปิดโครงการ", strAmount, "-" + strAmount
                            , "2", strEmpSeq);
                    }
                }

                projectBLL.DeleteProject(strBgmProjSeq, strEmpSeq);
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "onclick", "closeRadWindow", true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
         
    }
}